local Sol = LibStub("Sol");
local nkLibQuests = LibStub("nkLibQuests");
local nkLibChannels = LibStub("nkLibChannels");

nkPartyQuest.UI = {};
nkPartyQuest.UI.MAXTABSIZE = 3;

nkPartyQuest.UI.TopQuest = 1;

-- Sets the names of the players in the overview
-- Input:	None
-- Output:	None
nkPartyQuest.UI.SetPlayerNames = function ()

	local playerText = getglobal("nkPartyQuestFrame_Players_Name1");
	
	if (playerText) then
		playerText:SetText(UnitName("player"));
	end;

	for idx = 2, 6 do
		local playerText = getglobal("nkPartyQuestFrame_Players_Name" .. idx);
		
		if(UnitExists("party1")) then
			if (UnitExists("party"..(idx-1))) then
				playerText:SetText(UnitName("party"..(idx-1)));
			else
				playerText:SetText ("");
			end;
		else
			playerText:SetText ("");
		end; 
	end;

end;

-- Handles the update of the UI
-- Input:	None
-- Output:	None
nkPartyQuest.UI.UpdateUI = function ()

	nkPartyQuest.UI.SetPlayerNames();

	if (nkPartyQuest.Core.QuestList[UnitName("player")] ~= nil) then
		--DEFAULT_CHAT_FRAME:AddMessage ("Loading Quests");
		nkPartyQuest.UI.UpdateQuestOverview(0);
	else
		--DEFAULT_CHAT_FRAME:AddMessage ("Clear all GUI lines");
		nkPartyQuest.UI.ClearQuestLines (1);
	end;
		
	nkPartyQuest.UI.QuestOverview_ScrollBar_UpdateRangeChanged();		

end;

-- Updates the range of the scrollbar
-- Input:	None
-- Output:	None
nkPartyQuest.UI.QuestOverview_ScrollBar_UpdateRangeChanged = function ()

	local maxline = GetNumQuestBookButton_QuestBook();
	
	if maxline > 10 then
		nkPartyQuestFrame_Content_ScrollBar:SetMinMaxValues(0, maxline - 10);
		nkPartyQuestFrame_Content_ScrollBar:SetValue(0);
	else
		nkPartyQuestFrame_Content_ScrollBar:SetMinMaxValues(0, 0);
	end
	
	UIPanelScrollBar_OnValueChanged(nkPartyQuestFrame_Content_ScrollBar, 0);
	
end

nkPartyQuest.UI.QuestHistory_ScrollBar_UpdateRangeChanged = function (questlist)

	if questlist == nil then
		questlist = nkPartyQuest.Quests.GetHistoryQuests();
	end;
	
	if questlist == nil then 
		nkPartyQuestFrame_HISTORY_ScrollBar:SetMinMaxValues(0, 0);
	elseif #questlist == 0 or #questlist <= 10 then
		nkPartyQuestFrame_HISTORY_ScrollBar:SetMinMaxValues(0, 0);
	else		
		nkPartyQuestFrame_HISTORY_ScrollBar:SetMinMaxValues(0, #questlist - 10);
		nkPartyQuestFrame_HISTORY_ScrollBar:SetValue(0);			
	end;
	
end;

-- Loads the quest information into the UI
-- Input:	StartNo	- the first quest to show
-- Output:	None
nkPartyQuest.UI.UpdateQuestOverview = function (StartNo)

	nkPartyQuest.UI.TopQuest = StartNo;
	local SortedQList = nkPartyQuest.Quests.GetSortedQuestList (nkPartyQuest.Core.QuestList[UnitName("player")]);

	--DEFAULT_CHAT_FRAME:AddMessage ("Size of sorted list: " .. #SortedQList);

	for idx = 1, 10 do
		if (StartNo + idx > #SortedQList) then
			nkPartyQuest.UI.ClearQuestLines (idx);
			break;
		else		
			local QuestDetails = nkPartyQuest.Core.QuestList[UnitName("player")] [SortedQList[StartNo + idx].ident];		
			local QuestName = getglobal ("nkPartyQuestFrame_Content_Line" .. idx .. "_QuestTitle");			
		
			if QuestName then
				local RoleLV	= GetCurrentVocLV();
				local LV		= RoleLV - QuestDetails.level;
			
				QuestName:SetText (SortedQList[StartNo + idx].name);
				
				if( LV <= -3 ) then
					QuestName:SetColor( 1, 0, 0 );
				elseif( LV >= 3 ) then
					QuestName:SetColor( 0, 0.7, 0 );
				else
					QuestName:SetColor( 1, 1, 0 );
				end
				
				QuestName:Show();
		
				nkPartyQuest.UI.SetQuestStatus(idx, 1, QuestDetails.status);
									
				for idx2 = 2, 6 do
					local playerText = getglobal("nkPartyQuestFrame_Players_Name" .. (idx2));
					if playerText then
						local playername = playerText:GetText();
						if (playername == "") then
							-- no player on this spot
							nkPartyQuest.UI.SetQuestStatus(idx, idx2, -1);
						elseif nkPartyQuest.Core.QuestList[playername] ~= nil then
							-- got quest info from that player
						
							local tmpIdent = SortedQList[StartNo + idx].ident;
							local tmpQuestDetails = nkPartyQuest.Core.QuestList[playername];
							
							if tmpQuestDetails[tmpIdent] == nil then
								-- Player does not have quest
								--DEFAULT_CHAT_FRAME:AddMessage("Player " .. playername .. " does not have quest " .. tmpIdent);
								nkPartyQuest.UI.SetQuestStatus(idx, idx2, 0);
							else
								-- Player is on quest
								--DEFAULT_CHAT_FRAME:AddMessage("Player " .. playername .. " quest status for " .. tmpIdent .. " " .. tmpQuestDetails[tmpIdent].status);
								nkPartyQuest.UI.SetQuestStatus(idx, idx2, tonumber(tmpQuestDetails[tmpIdent].status));
							end;		
						else
							-- player in group but not info, probably not using addon
							--DEFAULT_CHAT_FRAME:AddMessage("Player " .. playername .. " no info");							
							nkPartyQuest.UI.SetQuestStatus(idx, idx2, -1);	
						end;
					end;
				end;
			end;			
		end;
	end;
end;


-- Sets the status of a quest in the overview
-- Input:	line	- the quest line (1-10)
--			player	- the player index (1-6)
--			status	- the status of the quest
--					   -1 -> Hide quest status
--						0 -> does not have quest
--						1 -> quest not finished
--						9 -> quest finished
nkPartyQuest.UI.SetQuestStatus = function (line, player, status)

	local QuestStatus = getglobal ("nkPartyQuestFrame_Content_Line" .. line .. "_P" .. player);
	
	--DEFAULT_CHAT_FRAME:AddMessage("updating line " .. line .. " of player " .. player .. " with status " .. status);
	
	if QuestStatus then
		local QuestStatusIcon = getglobal (QuestStatus:GetName() .. "_Icon");
		
		if QuestStatusIcon then
			if (status == -1) then
				QuestStatusIcon:SetAlpha(0);
			elseif (status == 9) then
				QuestStatusIcon:SetFile("Interface/buttons/checkbox-checked-disabled.tga");
				QuestStatusIcon:SetColor(unpack{0.5, 1.0, 0.5});
				QuestStatusIcon:SetAlpha(1.0);
			elseif (status == 1) then
				QuestStatusIcon:SetFile("Interface/itemmall/shoppinghistory-disable.tga");
				QuestStatusIcon:SetColor(unpack{0.5, 0.5, 1.0});
				QuestStatusIcon:SetAlpha(0.75);
			else
				QuestStatusIcon:SetFile("Interface/itemmall/shoppinghistorydel-disable.tga");
				QuestStatusIcon:SetColor(unpack{1, 1, 1});
				QuestStatusIcon:SetAlpha(0.25);
			end;
		end;

		QuestStatus:Show();
			
	end;
end;

-- Clears the excess quests lines if player has less than 10 active quests
-- Input:	StartLine	- the first line to hide
-- Output:	None
nkPartyQuest.UI.ClearQuestLines = function (StartLine)
	
	--DEFAULT_CHAT_FRAME:AddMessage ("Clearing GUI lines " .. StartLine .. " to 10");
	
	for idx = StartLine, 10 do
	
		local QuestName = getglobal ("nkPartyQuestFrame_Content_Line" .. idx .. "_QuestTitle");
		QuestName:SetText ("");
		QuestName:Hide();
		
		for idx2 = 1, 6 do		
			local QuestStatus = getglobal ("nkPartyQuestFrame_Content_Line" .. idx .. "_P" .. idx2);
			QuestStatus:Hide();
		end;
	end;
end;

-- Builds and displays the tooltip for the quest overview
--
nkPartyQuest.UI.ToolTip = function(frame)
	
	local QuestName = getglobal(frame:GetName().. "_QuestTitle"):GetText();
	local QuestDetails = nkPartyQuest.Quests.GetQuestDetailsByName(QuestName);
	
	if QuestDetails == nil then
		-- Quest not found
		--DEFAULT_CHAT_FRAME:AddMessage ("quest not found");
		return;
	end;
	
	local green = {"|cff00D300"; {1, 0, 0}};
	local yellow = {"|cffF4F400"; {1, 1, 0}};
	local red = {"|cffE70000"; {0, 0.7, 0}};
			
	local CatalogName = GetQuestCatalogInfo(QuestDetails.catalogID);
	ViewQuest_QuestBook(QuestDetails.index);
		 	
	local GToolTip = _G["GameTooltip"];
	GToolTip:ClearAllAnchors();
	GToolTip:SetOwner(frame, "ANCHOR_TOPLEFT", 25, 25);
	GToolTip:ClearLines();
	
	local RoleLV	= GetCurrentVocLV();
	local LV		= RoleLV - tonumber(QuestDetails.level);
			
	if( LV <= -3 ) then
		GToolTip:SetText(QuestName, unpack(green[2]));
	elseif( LV >= 3 ) then
		GToolTip:SetText(QuestName, unpack(red[2]));
	else
		GToolTip:SetText(QuestName, unpack(yellow[2]));
	end
	
	GToolTip:AddLine("Level: ".. QuestDetails.level); 
    if (CatalogName) then GToolTip:AddLine(CatalogName); end;
    if (QuestDetails.RewardNPCInfo) then
    	GToolTip:AddLine("|cffFF0000NPC: " .. QuestDetails.RewardNPCInfo[2]);
    	GToolTip:AddLine(	"(" .. 
    						GetZoneLocalName(QuestDetails.RewardNPCInfo[3]) .. 
    						" " ..
    						string.format("%0.1f", QuestDetails.RewardNPCInfo[4] * 100) .. 
    						", "..
							string.format("%0.1f", QuestDetails.RewardNPCInfo[5] * 100) ..
    						")|r");
    end;
    GToolTip:AddLine("|cffF46700XP: " .. QuestDetails.exp .. "|r - |cff1187DBTP: " .. QuestDetails.tp .. "|r - |cffFFFF00Gold: " .. QuestDetails.money .. "|r");
    
    local index = nkLibQuests.GetQuestIndexByName (QuestName);
    
    if index ~= nil then
    	local NumRequest = GetQuestRequest( index, -1 );
    
 		if( NumRequest ~= 0 ) then
 			GToolTip:AddLine("\n");
 	
    		for idx = 1, NumRequest, 1 do
				Text, IsFinish 	= GetQuestRequest( index, idx );
				
				if IsFinish then				
					GToolTip:AddLine( green[1] .. nkLibQuests.CleanQuestName(Text) .. "|r");
				else
					GToolTip:AddLine( yellow[1] .. Text .. "|r");
				end;
			end;
		end;
	end;
	
    GToolTip:AddLine("\n" .. QuestDetails.detail);
    
    GToolTip:Show();
end;


-- Displays the quest overview UI
--
nkPartyQuest.UI.ShowFrame = function ()
	
	nkPartyQuestFrame_Title:SetText("|cffFFD800" .. nkPartyQuest.AddonName .. " " .. nkPartyQuest.AddonVersion .. "|r");
	nkPartyQuestFrame_ChannelStatus_Title:SetText("|cffFFD800" .. nkPartyQuest.Lang.Common.CHANSTATTILE .. "|r");

	if (nkLibChannels.IsChannelAvailable (nkPartyQuest.Com.ChannelName) == true) then
		-- Channel available		
		nkPartyQuestFrame_ChannelStatus_Info:SetText("|cff15B500" .. nkPartyQuest.Lang.Common.ONLINE .. "|r");
	else
		-- Channel not available			
		nkPartyQuestFrame_ChannelStatus_Info:SetText("|cffFF0000" .. nkPartyQuest.Lang.Common.OFFLINE .. "|r");
	end;
	
	nkPartyQuestFrame_Tab1:SetText(nkPartyQuest.Lang.UI["TAB1"]);
	nkPartyQuestFrame_Tab2:SetText(nkPartyQuest.Lang.UI["TAB2"]);
	nkPartyQuestFrame_Tab3:SetText(nkPartyQuest.Lang.UI["TAB3"]);

	for i = 1, nkPartyQuest.UI.MAXTABSIZE do
	    local tab = getglobal('nkPartyQuestFrame_Tab'..i);
   		if tab then
   			tab:Show();
			UIPanelTab_SetActiveState(tab, false);
		end;
	end;
	
	nkPartyQuest.UI.UpdateUI();
	
	nkPartyQuestFrame_Catalog_Text:SetText(nkPartyQuest.Lang.UI.AREA);
	
	local tmpCatalogNames = nkPartyQuest.Quests.GetCatalogList();
	
	if tmpCatalogNames ~= nil then
		Sol.config.SetupDropdown(nkPartyQuestFrame_Catalog, tmpCatalogNames, 1, 200, nkPartyQuest.UI.ShowHistoryQuests);
		nkPartyQuest.UI.UpdateQuestHistory (0, tmpCatalogNames[1]);
	end;
		
	nkPartyQuestFrame_ABOUT_TEXT:SetText(nkPartyQuest.Lang.UI.DEVBY .. " Naifu aka Dorobo\n\nemail: naifukishi@gmail.com");
	
	local tab = getglobal('nkPartyQuestFrame_Tab1');
	UIPanelTab_SetActiveState(tab, true);	
		
end;

nkPartyQuest.UI.SwitchTab = function (buttonID)

	local TabList = {"OVERVIEW", "HISTORY", "ABOUT" };
	
	for i = 1, nkPartyQuest.UI.MAXTABSIZE do
	    local tab = getglobal('nkPartyQuestFrame_Tab'..tostring(i)); 
	    
	    if tab then
  			local Frame = _G["nkPartyQuestFrame_" .. TabList[i]];
    		
    		if (buttonID == i) then
    			Frame:Show();
    			UIPanelTab_SetActiveState(tab, true);
    		else
    			Frame:Hide();
    			UIPanelTab_SetActiveState(tab, false);    			
    		end;    				
    	end;
    end;
end;

nkPartyQuest.UI.ShowHistoryQuests =  function (dropdown, selectedIndex, selectedValue)
	
	nkPartyQuest.UI.UpdateQuestHistory (0, selectedValue);
	
end;
			
nkPartyQuest.UI.UpdateQuestHistory = function (StartNo, catalogName)

	if catalogName == nil then
		local catalogdd = getglobal ("nkPartyQuestFrame_Catalog");
		catalogID = UIDropDownMenu_GetSelectedID (catalogdd);
		local tmpCatalogNames = nkPartyQuest.Quests.GetCatalogList();		
		catalogName = tmpCatalogNames [catalogID]; 
		
		if catalogName == nil then
			return;
		end;		
	end;
	
	local tmpQuestList = nkPartyQuest.Quests.GetHistoryQuests (catalogName);
	
	for idx = 1, 10, 1 do
		local historyline = getglobal ("nkPartyQuestFrame_HISTORY_Line" .. (idx) .. "_QuestTitle")

		if StartNo + idx > #tmpQuestList then
			historyline:SetText ("");
		else							
			historyline:SetText (tmpQuestList[(StartNo + idx)].name);
		end;
	end;
	
	if StartNo == 0 then nkPartyQuest.UI.QuestHistory_ScrollBar_UpdateRangeChanged(tmpQuestList); end;	
	
			
end;
